package com.decent.ejfadmin.utils;

import com.allinpay.ets.client.util.MySecureProtocolSocketFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.apache.commons.lang.ArrayUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.SocketTimeoutException;

/**
 * describe:http工具类
 *
 * @author 陈豆豆
 * @date 2019/09/07
 */
@Slf4j
public final class EjfHttpclient {

    /****
     * URL GET连接
     *
     * @param url         get访问URL地址
     * @param charset     编码格式
     * @param conntimeout 连接超时时间
     * @param sotimeout   读取超时时间
     * @param fag         boolean 是否为多线程操作TRUE 为多线程操作，FALSE为非多线程操作
     * @return
     */
    public static String Get(String url, String charset, int conntimeout, int sotimeout, boolean fag) {
        String returnStr = "";
        HttpMethod method = null;
        try {
            HttpClient client;
            if (fag) {
                MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
                client = new HttpClient(connectionManager);
            } else {
                client = new HttpClient();
            }
            client.getHttpConnectionManager().getParams().setConnectionTimeout(conntimeout);
            client.getHttpConnectionManager().getParams().setSoTimeout(sotimeout);
            method = new GetMethod(url);
            method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, charset);
            client.executeMethod(method);
            BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset));
            StringBuffer stringBuffer = new StringBuffer(100);
            String str;
            while ((str = reader.readLine()) != null) {
                stringBuffer.append(str);
            }
            returnStr = stringBuffer.toString();
        } catch (Exception e) {
            log.warn("连接发生异常：" + url, e);
        } finally {
            method.releaseConnection();
        }
        return returnStr;
    }

    /****
     * URL POST访问
     *
     * @param url         地址
     * @param data        POST内容
     * @param charset     编码格式
     * @param conntimeout 连接超时时间
     * @param sotimeout   读取超时时间
     * @param fag         boolean 是否为多线程操作TRUE 为多线程操作，FALSE为非多线程操作
     * @return
     */
    public static String Post(String url, NameValuePair[] data, String charset, int conntimeout, int sotimeout, boolean fag) {
        String returnStr = "";
        PostMethod postMethod = null;
        try {
            HttpClient client;
            if (fag) {
                MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
                client = new HttpClient(connectionManager);
            } else {
                client = new HttpClient();
            }
            postMethod = new PostMethod(url);
            postMethod.setRequestBody(data);
            client.getHttpConnectionManager().getParams().setConnectionTimeout(conntimeout);
            client.getHttpConnectionManager().getParams().setSoTimeout(sotimeout);
            client.executeMethod(postMethod);
            returnStr = postMethod.getResponseBodyAsString();
        } catch (Exception e) {
            StringBuffer error = new StringBuffer(1000);
            error.append("连接发生异常：").append(url).append("\t");
            error.append("提交数据为：").append(data.toString()).append("\t");
            log.warn(error.toString(), e);
        } finally {
            postMethod.releaseConnection();
        }
        return returnStr;
    }

    public static String Get(String url) {
        String returnStr = "";
        HttpMethod method = null;
        try {
            ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory();
            Protocol.registerProtocol("https", new Protocol("https", fcty, 443));
            HttpClient client = new HttpClient();
            client.getHostConfiguration().setProxy("10.46.166.16", 8888);
            client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
            client.getHttpConnectionManager().getParams().setSoTimeout(5000);
            method = new GetMethod(url);
            method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "GBK");
            method.setRequestHeader("Connection", "keep-alive");
            client.executeMethod(method);
            BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
            StringBuffer stringBuffer = new StringBuffer(100);
            String str;
            while ((str = reader.readLine()) != null) {
                stringBuffer.append(str);
            }
            returnStr = stringBuffer.toString();
        } catch (Exception e) {
            log.warn("连接发生异常：" + url, e);
            // 读取超时
            if (e.getLocalizedMessage().indexOf("Read timed out") != -1
                    || e.getLocalizedMessage().indexOf("read timed out") != -1) {
                return "OK";
            }
        } finally {
            method.releaseConnection();
        }
        return returnStr;
    }

    public static String Post(String url, Part[] parts, String charset) {
        String returnStr = "";
        PostMethod postMethod = null;
        try {
            postMethod = new PostMethod(url);
            postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, charset);
            postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
            HttpClient clients = new HttpClient();
            clients.executeMethod(postMethod);
            try {
                BufferedReader rd = new BufferedReader(new InputStreamReader(postMethod.getResponseBodyAsStream(), "UTF-8"));
                StringBuffer stringBuffer = new StringBuffer(500);
                String line;
                while ((line = rd.readLine()) != null) {
                    stringBuffer.append(line);
                }
                rd.close();
                returnStr = stringBuffer.toString();
            } catch (Exception e) {
                StringBuffer error = new StringBuffer(1000);
                error.append("连接发生异常：").append(url).append("\t");
                error.append("提交数据为：").append(parts.toString()).append("\t");
                log.warn(error.toString(), e);
            }
        } catch (Exception e) {
            log.warn("提交发生异常 地址[" + url + "] 提交数据[" + ArrayUtils.toString(parts) + "]");
        } finally {
            postMethod.releaseConnection();
        }
        return returnStr;
    }

    public static String Post_try(String url, NameValuePair[] data, String charset, int conntimeout, int sotimeout, boolean fag) {
        String returnStr;
        PostMethod postMethod = null;
        try {
            HttpClient client;
            if (fag) {
                MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
                client = new HttpClient(connectionManager);
            } else {
                client = new HttpClient();
            }
            postMethod = new PostMethod(url);
            postMethod.setRequestBody(data);
            client.getHttpConnectionManager().getParams().setConnectionTimeout(conntimeout);
            client.getHttpConnectionManager().getParams().setSoTimeout(sotimeout);
            client.executeMethod(postMethod);
            returnStr = postMethod.getResponseBodyAsString();
        } catch (ConnectTimeoutException e) {//连接超时
            log.error("地址[{}]连接超时", url, e, e);
            return "连接超时";
        } catch (SocketTimeoutException e) {//读取超时
            log.error("地址[{}]读取超时", url, e, e);
            return "读取超时";
        } catch (Exception e) {
            log.error("地址[{}]连接异常", url, e, e);
            return "连接发生异常";
        } finally {
            postMethod.releaseConnection();
        }
        return returnStr;
    }
}
